package ru.reinvent.perspectiva.fragments;

import java.io.File;
import java.util.ArrayList;
import java.util.Hashtable;

import com.actionbarsherlock.app.SherlockFragment;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.download.URLConnectionImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;

import ru.reinvent.perspectiva.R;
import ru.reinvent.perspectiva.cash.Lot;
import ru.reinvent.perspectiva.cash.PerspectivaProvider;
import ru.reinvent.perspectiva.cash.PerspectivaProvider.L;
import ru.reinvent.perspectiva.cash.PerspectivaProvider.V;
import ru.reinvent.perspectiva.cash.Vendor;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Filter;

public class CatalogFragment extends SherlockFragment {
	protected ListView msglist;
	protected ArrayList<Lot> lots;
	protected Hashtable<Integer,String> vendorsNames;
	protected AsyncDBLoader dbLoader;
	protected FragmentListener listener;
	// public BackGroundLoader loader;
	protected ArrayAdapter<Lot> adapter;
	protected Boolean isFiltered = false;
	protected ImageLoader imageLoader;
	protected File cacheDir;
	protected DisplayImageOptions options;
	protected Activity activity;
	// public ArrayList<Message> newMessages;

	public CatalogFragment() {;}
	
	public CatalogFragment(FragmentListener listener) 
		{
		this.listener = listener;
		}
	
	@Override
	public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) 
		{
		this.activity = getActivity();
		if (msglist != null) 
			{
			if (msglist.getParent() != null) ((ViewGroup) msglist.getParent()).removeView(msglist);
			if (listener != null) listener.interfacePrepared();
			return msglist;
			}
		
		cacheDir = StorageUtils.getCacheDirectory(activity);
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
	        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"perspectiva");
	    else
	        cacheDir=activity.getCacheDir();
	    if(!cacheDir.exists())
	        cacheDir.mkdirs();
		imageLoader = ImageLoader.getInstance();
		
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(activity)
		.memoryCache(new WeakMemoryCache())
		.denyCacheImageMultipleSizesInMemory()
		.discCache(new UnlimitedDiscCache(cacheDir))
		.imageDownloader(new URLConnectionImageDownloader(120 * 1000, 120 * 1000))
		.enableLogging()
		.build();
		
		options = new DisplayImageOptions.Builder()
		.resetViewBeforeLoading()
		.cacheOnDisc()
		.build();
		
		imageLoader.init(config);
		
		msglist = new ListView(activity);
		msglist.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		msglist.setCacheColorHint(Color.TRANSPARENT);
		msglist.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
/*				HashMap<String, String> hashmap = new HashMap<String,String>();
				hashmap.put("imgLink", lots.get(arg2).getImageUrl());
				hashmap.put("descr", lots.get(arg2).getDescription());
				hashmap.put("vendor", vendorsNames.get(lots.get(arg2).getVendorId()));
				hashmap.put("name", lots.get(arg2).getName());
				hashmap.put("adddate", String.valueOf(lots.get(arg2).getAddDate()));
				hashmap.put("price", lots.get(arg2).getPrice());
				hashmap.put("refference", lots.get(arg2).getReference());
				hashmap.put("case", lots.get(arg2).getHull());
				hashmap.put("gender", lots.get(arg2).getGender());
				hashmap.put("type", lots.get(arg2).getType());
				hashmap.put("state", lots.get(arg2).getState());
				hashmap.put("region", lots.get(arg2).getRegion());
*/
				if (listener != null) listener.listViewItemClicked(lots.get(arg2).getId());
			}});
		
		if (!PerspectivaProvider.DBUsage.isLotsEmpty(activity) && !PerspectivaProvider.DBUsage.isVendorsEmpty(activity))
			startFillContent();
		
		return msglist;
		}
	
	public void setFragmentListener(FragmentListener listener)
		{
		this.listener = listener;
		}
	
	public FragmentListener getFragmentListener()
		{
		return listener;
		}
	
	public void startFillContent()
		{
		stopFillContent();
		dbLoader = new AsyncDBLoader();
		dbLoader.execute();
		}
	
	public void stopFillContent()
		{
		if (dbLoader == null) return;
		if (dbLoader.getStatus() == AsyncTask.Status.RUNNING) dbLoader.cancel(true);
		}
	
	public ArrayAdapter<Lot> getAdapter()
		{
		return adapter;
		}
	
	protected class PerformanceArrayAdapter extends ArrayAdapter<Lot> {
		public ArrayList<Lot> messages, allMessages, filterMessages,
				buffer;
		public Filter filter;
		public int pageCounter = 0;
		public int sizeOfList = 0;
		public Bitmap finalImage;

		class ViewHolder {
			public TextView title, vendor, price;
			public ImageView image;
			public ImageLoadingListener imgViewBgChanger;
			public int mTask;
		}

		public PerformanceArrayAdapter(ArrayList<Lot> list) {
			super(activity, R.layout.catalog_item, list);
			// Р±СѓС„С„РµСЂ РґР»СЏ РѕС‚СЃР»РµР¶РёРІР°РЅРёСЏ РёР·РјРµРЅРµРЅРёСЏ
			// Р’РЎР•РҐ Р·Р°РїРёСЃРµР№
			this.buffer = list;
			this.allMessages = new ArrayList<Lot>();
			allMessages.addAll(buffer);
			// this.messages = allMessages;
			this.messages = new ArrayList<Lot>();
			messages.addAll(allMessages);
			getFilter();
			
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			// РїСЂРѕРІРµСЂСЏРµРј, РёР·РјРµРЅРёР»РѕСЃСЊ Р»Рё РєРѕР»-РІРѕ
			// Р’РЎР•РҐ Р·Р°РїРёСЃРµР№
			if (buffer.size() > sizeOfList) {
				// РµСЃР»Рё РґРѕРіСЂСѓР·РёР»Рё РЅРѕРІС‹Рµ РѕР±СЉСЏРІР»РµРЅРёСЏ,
				// Р·Р°РїРѕР»РЅСЏРµРј
				this.allMessages = new ArrayList<Lot>();
				allMessages.addAll(buffer);
				this.messages = new ArrayList<Lot>();
				messages.addAll(allMessages);
				sizeOfList = allMessages.size();
			}

			View rowView = convertView;
			if (rowView == null) {
				LayoutInflater inflater = activity.getLayoutInflater();
				rowView = inflater.inflate(R.layout.catalog_item, null);
				
				final ViewHolder viewHolder = new ViewHolder();
				viewHolder.title = (TextView) rowView.findViewById(R.id.catalog_item_lot);
				viewHolder.image = (ImageView) rowView.findViewById(R.id.catalog_item_clock_icon);
				viewHolder.price = (TextView) rowView.findViewById(R.id.catalog_item_price);
				viewHolder.vendor = (TextView) rowView.findViewById(R.id.catalog_item_vendor);
				viewHolder.imgViewBgChanger = new ImageLoadingAdapter(viewHolder.image); 
				
				rowView.setTag(viewHolder);
			}

			final ViewHolder holder = (ViewHolder) rowView.getTag();

			holder.title.setText(messages.get(position).getName());
			holder.vendor.setText(vendorsNames.get(messages.get(position).getVendorId()));
			holder.price.setText(messages.get(position).getPrice());
			holder.image.setBackgroundColor(Color.BLACK);

			final String correctImageUrl = messages.get(position).getImageUrl().replace(" ", "%20");
			imageLoader.displayImage(correctImageUrl, holder.image, options, holder.imgViewBgChanger);
			
			return rowView;
		}

		@Override
		public Filter getFilter() {
			if (filter == null) {
				filter = new MessagesFilter();
			}

			return filter;
		}

		private class ImageLoadingAdapter implements ImageLoadingListener {
			
			private ImageView imgView;
			
			public ImageLoadingAdapter(ImageView imgView) {
				this.imgView = imgView;
			}
			
			@Override
			public void onLoadingComplete(Bitmap bmp) {
				imgView.setBackgroundColor(bmp.getPixel(0,0));
			}
			
			@Override
			public void onLoadingCancelled() {;}
			@Override
			public void onLoadingFailed(FailReason fr) {;}
			@Override
			public void onLoadingStarted() {;}
		}
		
		private class MessagesFilter extends Filter {

			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				constraint = constraint.toString().toLowerCase();
				FilterResults result = new FilterResults();
				// Р·Р°РїРѕР»РЅСЏРµРј Р»РёСЃС‚ Р·Р°РїРёСЃРµР№ РІ
				// СЃРѕРѕС‚РІРµС‚СЃРІРёРё СЃРѕ Р·РЅР°С‡РµРЅРёРµРј С„РёР»СЊС‚СЂР°
				if (constraint != null && constraint.toString().length() > 0) {
					ArrayList<Lot> founded = new ArrayList<Lot>();
					for (int i = 0; i < allMessages.size(); i++) {
						Lot m = allMessages.get(i);
						if (m.getName().toLowerCase().contains(constraint))
							founded.add(m);
					}
					result.values = founded;
					result.count = founded.size();
				} else {
					result.values = allMessages;
					result.count = allMessages.size();
				}

				return result;
			}

			@SuppressWarnings("unchecked")
			@Override
			protected void publishResults(CharSequence constraint,
					FilterResults results) {
				clear();

				messages = (ArrayList<Lot>) results.values;
				for (int i = 0; i < messages.size(); i++) {
					add(messages.get(i));
					notifyDataSetChanged();
				}

			}

		}

	}
	
	protected class AsyncDBLoader extends AsyncTask<Void,Void,Object[]>
		{
		boolean working = true;
			
		@Override
		protected Object[] doInBackground(Void... params) 
			{
			ArrayList<Lot> lots = new ArrayList<Lot>();
			Hashtable<Integer, String> vendorsNames = new Hashtable<Integer, String>();
			
			Cursor c = activity.getContentResolver().query(L.CONTENT_URI,null,null,null,null);
			c.moveToFirst();
			while (c.moveToNext() && working) lots.add(PerspectivaProvider.DBUsage.createLot(c));
			
			c = activity.getContentResolver().query(V.CONTENT_URI,null,null,null,null);
			c.moveToFirst();
			
			Vendor vnd;
			while(c.moveToNext() && working) 
				{
				vnd = PerspectivaProvider.DBUsage.createVendor(c);
				vendorsNames.put(vnd.getId(),vnd.getName());
				}

			Object[] ret = { lots, vendorsNames };
			return ret;
			}

		@Override
		protected void onCancelled()
			{
			working = false;
			}
		
	    @SuppressWarnings("unchecked")
		@Override
		protected void onPostExecute(Object[] result) 
	    	{
			lots = (ArrayList<Lot>) result[0];
			vendorsNames = (Hashtable<Integer, String>) result[1];
			
			adapter = new PerformanceArrayAdapter(lots);
			msglist.setAdapter(adapter);	
			
			if (listener != null) listener.interfacePrepared();
	    	}
		}
	
	public interface FragmentListener
		{
		public void interfacePrepared();
		public void listViewItemClicked(int lotId);
		}

}
